package bad;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.sip.SipApplicationSession;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.TooManyHopsException;
import javax.servlet.sip.URI;

public class SipClient extends SipServlet
{
	private static final String SERVER_URL = "127.0.0.1:5077";

	@Resource
	private SipFactory factory;

	@Override
	protected void doAck(SipServletRequest req) throws ServletException,
			IOException
	{
		System.out.println("From: " + req.getHeader("From") + "\nTo: " + req.getHeader("To") + "\nmsg: " + req.getHeader("From")
				+ "\nsessionId: " + req.getSession().getId());
		super.doAck(req);
	}

	@Override
	protected void doResponse(SipServletResponse resp) throws ServletException,
			IOException
	{
		super.doResponse(resp);
	}

	@Override
	protected void doMessage(SipServletRequest req) throws ServletException,
			IOException
	{
		System.out.println(req.getContentType());
		System.out.println((String) req.getContent());
		super.doMessage(req);
	}

	protected void sendMessage(String msg, URI from, URI to) throws IOException, TooManyHopsException
	{
		SipApplicationSession session;
		SipServletRequest echo;
		synchronized (factory)
		{
			session = factory.createApplicationSession();
			echo = factory.createRequest(session, msg, from, to);
			echo.pushRoute(factory.createSipURI("127.0.0.1", "22222"));
			System.out.println(echo.getProxy());
		}
		System.out.println("From: " + from + "\nTo: " + to + "\nmsg: " + msg
				+ "\nsessionId: " + session.getId());
//		echo.send();
	}
	
	public static void main(String[] args) throws TooManyHopsException, IOException{
		new SipClient().launch();
	}

	private void launch() throws TooManyHopsException, IOException
	{
		factory = (SipFactory)getServletContext().getAttribute("javax.servlet.sip.SipFactory");
		sendMessage("Good",
				factory.createSipURI("127.0.0.1", "222222"),
				factory.createSipURI("127.0.0.1", "5077"));
	}
	
}
